/*
 * Copyright (C) 2012 Google Inc.  All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Controls the discoveryClient object.  The discoveryClient object is created
 * by the googletvremote plugin during initialization.
 *
 * The discovery client searches for Anymote sessions on the local network.
 * This is the recommended way to find Google TV devices.  However some networks
 * may block the Discovery Client.  If that occurs you can attempt to pair with
 * a device by manually entering an IP address and assuming the Anymote port is
 * 9551.  Ideally the discovery client would determine the Anymote port, but all
 * existing Google TV's use port 9551, so that is a good guess if the discovery
 * client fails.  The discovery client functions include:
 *     startDiscovery(advertisedDeviceCallback, errorCallback)
 *     stopDiscovery()
 */


/** Discovery client object that this controller manages. */
var discoveryClient;


/** Id of a timer that is used to automatically stop discovery. */
var stopDiscoveryClientTimerId;


/** Start searching for Anymote services advertised on the local network. */
var startDiscoveryClient = function() {
  // DONE: Start the discovery client.
  // Create a callback to display Google TV devices on this network.
  var ipAddressEl = document.getElementById('ip-address');
  discoveryClient.startDiscovery(function(advertisedDevice) {
    // The discovery client returns the following information about the device.
    console.log('serviceName = ' + advertisedDevice.serviceName); // Not needed
    console.log('instanceName = ' + advertisedDevice.instanceName); // Nonsense
    console.log('address = ' + advertisedDevice.address); // IP address (useful)
    console.log('servicePort = ' + advertisedDevice.servicePort);  // 9551

    // Add the IP address to the UI and make it clickable.
    var deviceList = document.getElementById('discovered-devices-list');
    var deviceIpEl = document.createElement('span');
    deviceIpEl.innerHTML = advertisedDevice.address + ' ';
    deviceIpEl.addEventListener('click', function() {
      ipAddressEl.value = advertisedDevice.address;
    });
    deviceList.appendChild(deviceIpEl);
    // Auto fill the ip-address field with the first hit (best guess).
    if (ipAddressEl.value.length == 0) {
      ipAddressEl.value = advertisedDevice.address;
    }
  }, function() {
    console.log('Error starting discovery client.');
    // For an error like this you should remove and restart the plugin.
  });

  // DONE: Set a timer to stop discover after a short time interval.
  stopDiscoveryClientTimerId = window.setTimeout(function() {
    // displayToast('Discovery client auto stopped.');
    stopDiscoveryClient();
  }, 5000);  // Auto stop discovery after 5 seconds.
};


/** Stop searching for Anymote services advertised on the local network. */
var stopDiscoveryClient = function() {
  // DONE: Stop the discovery client.
  discoveryClient.stopDiscovery();
  // DONE: Clear the timer that will stop discovery.
  window.clearTimeout(stopDiscoveryClientTimerId);
};
